import {ExclamationCircleOutlined, PlusOutlined} from '@ant-design/icons';
import {Button, Drawer, message, Modal} from 'antd';
import React, { useState, useRef } from 'react';
import { useIntl, FormattedMessage } from 'umi';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import type { ProDescriptionsItemProps } from '@ant-design/pro-descriptions';
import ProDescriptions from '@ant-design/pro-descriptions';
import {addBusNo, fetchAllBusNo, rmBusNo, updateBusNo} from "@/services/BusNo";
import BusNoInfoForm from "@/pages/BusNo/component/BusNoInfoForm";
import {optMessage} from "@/utils/optMessage";

/**
 * @en-US Add node
 * @zh-CN 添加节点
 * @param fields
 */
const handleAdd = async (fields: Domain.BusNo) => {
  return await optMessage(async ()=>{
    await addBusNo(fields);
  },"添加");
};

const handleUpdate = async (fields:Domain.BusNo) => {
  await optMessage(async ()=>{
    await updateBusNo(fields);
  },"更新");
}

const BusNoDetail: React.FC = () => {


  const [showDetail, setShowDetail] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<Domain.BusNo>();
  const [selectedRowsState, setSelectedRows] = useState<Domain.BusNo[]>([]);

  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const intl = useIntl();

  const columns: ProColumns<Domain.BusNo>[] = [
    {
      title: (
        <FormattedMessage
          id="pages.busno.id"
          defaultMessage="ID"
        />
      ),
      dataIndex: 'id',
      tip: 'The id is the unique key',
      render: (dom, entity) => {
        return (
          <a
            onClick={() => {
              setCurrentRow(entity);
              setShowDetail(true);
            }}
          >
            {dom}
          </a>
        );
      },
    },
    {
      title: <FormattedMessage id="pages.busno.price" defaultMessage="Price" />,
      dataIndex: 'price',
      valueType: 'textarea',
      renderText: (val: string) => val+"元"
    },
    {
      title: (
        <FormattedMessage
          id="pages.busno.driverId"
          defaultMessage="id of drivers"
        />
      ),
      dataIndex: 'driverId',
      valueType: 'textarea'
    },
    {
      title: (
        <FormattedMessage
          id="pages.busno.busNum"
          defaultMessage="Bus Num"
        />
      ),
      dataIndex: 'busNum',
      valueType: 'textarea'
    },
    {
      title: (
        <FormattedMessage
          id="pages.busno.startStation"
          defaultMessage="Start Station"
        />
      ),
      dataIndex: 'startStation',
    },
    {
      title: (
        <FormattedMessage
          id="pages.busno.endStation"
          defaultMessage="End Station"
        />
      ),
      dataIndex: 'endStation',
    },
    {
      title: (
        <FormattedMessage
          id="pages.busno.fromTime"
          defaultMessage="From Time"
        />
      ),
      dataIndex: 'fromTime',
      valueType: 'dateTime'
    },
    {
      title: (
        <FormattedMessage
          id="pages.busno.toTime"
          defaultMessage="To Time"
        />
      ),
      dataIndex: 'toTime',
      valueType: 'dateTime'
    },
    {
      title: (
        <FormattedMessage
          id="pages.busno.realFrom"
          defaultMessage="Real From"
        />
      ),
      dataIndex: 'realFrom',
      valueType: 'dateTime',
      hideInSearch: true,
    },
    {
      title: (
        <FormattedMessage
          id="pages.busno.realTo"
          defaultMessage="RealTo"
        />
      ),
      dataIndex: 'realTo',
      valueType: 'dateTime',
      hideInSearch: true,
    },
    {
      title: <FormattedMessage id="pages.searchTable.titleOption" defaultMessage="Operating" />,
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <BusNoInfoForm
          // @ts-ignore
          trigger={
            <a key="update">
              <FormattedMessage id="pages.searchTable.update" defaultMessage="Update" />
            </a>
          }
          title="更新司机信息"
          handleUpdate={handleUpdate}
          busNo={record}
        />,
        <a key="delete"
           onClick={()=>{
             Modal.confirm({
               title: "是否确认删除车次 "+record.id+" ?",
               icon: <ExclamationCircleOutlined />,
               content: "删除后不可恢复",
               onOk (){
                 rmBusNo(record.id)
                   .then(()=>message.success("成功删除"))
                   .catch(()=>message.error("删除失败，请稍后重试"));
               }
             })
           }}>
          <FormattedMessage
            id="pages.searchTable.delete"
            defaultMessage="Delete"
          />
        </a>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable<Domain.BusNo, API.PageParams>
        headerTitle={intl.formatMessage({
          id: 'pages.searchTable.title',
          defaultMessage: 'Enquiry form',
        })}
        actionRef={actionRef}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <BusNoInfoForm
            // @ts-ignore
            trigger={
              <Button
                type="primary"
                key="primary"
              >
                <PlusOutlined /> <FormattedMessage id="pages.searchTable.new" defaultMessage="New" />
              </Button>
            }
            title="新建车次"
            handleAdd={handleAdd}
          />,
        ]}
        //@ts-ignore
        request={fetchAllBusNo}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              <FormattedMessage id="pages.searchTable.chosen" defaultMessage="Chosen" />{' '}
              <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a>{' '}
              <FormattedMessage id="pages.searchTable.item" defaultMessage="项" />
              &nbsp;&nbsp;
              <span>
                <FormattedMessage
                  id="pages.searchTable.totalServiceCalls"
                  defaultMessage="Total number of service calls"
                />{' '}
                {/*{selectedRowsState.reduce((pre, item) => pre + item.callNo!, 0)}{' '}*/}
                <FormattedMessage id="pages.searchTable.tenThousand" defaultMessage="万" />
              </span>
            </div>
          }
        >
          <Button
            onClick={async () => {
              // await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            <FormattedMessage
              id="pages.searchTable.batchDeletion"
              defaultMessage="Batch deletion"
            />
          </Button>
          <Button type="primary">
            <FormattedMessage
              id="pages.searchTable.batchApproval"
              defaultMessage="Batch approval"
            />
          </Button>
        </FooterToolbar>
      )}

      <Drawer
        width={600}
        visible={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.id && (
          <ProDescriptions<Domain.BusNo>
            column={2}
            title={currentRow?.id}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.id,
            }}
            columns={columns as ProDescriptionsItemProps<Domain.BusNo>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default BusNoDetail;
